<!-- 商户申请审核 -->
<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form :model="queryParams" label-width="80px" inline>
        <el-form-item label="公司名称" prop="keyword">
          <el-input v-model="queryParams.keyword" placeholder="请输入公司名称/公司别名" />
        </el-form-item>
        <el-form-item label="审核状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择" clearable style="width: 140px">
            <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker v-model="tempTime" :editable="false" type="datetimerange" range-separator="~"
            start-placeholder="开始时间" end-placeholder="截止时间" value-format="YYYY-MM-DD HH:mm:ss" @change="handleChange" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleSearch">搜索</el-button>
          <el-button icon="refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-tabs v-model="activeName" class="enter-tabs" @tab-change="handleClick">
      <el-tab-pane label="公司" name="company"></el-tab-pane>
      <el-tab-pane label="个人" name="designer" disabled></el-tab-pane>
    </el-tabs>
    <div class="table-container">
      <base-page-table :table-data="tableData" :table-columns-data="tableColumnsData" :loading="loading"
        :page-num="queryParams.pageNum" :page-size="queryParams.pageSize" :total="queryParams.total"
        @handleQuery="handleQuery">
        <template #userNickname="scope">
          <span>{{ scope.row?.merchantUserVO?.nickname }}</span>
        </template>
        <template #userMobile="scope">
          <span>{{ scope.row?.merchantUserVO?.mobile }}</span>
        </template>
        <template #nickname="scope">
          <span>{{ scope.row?.merchantUser?.nickname }}</span>
        </template>
        <template #mobile="scope">
          <span>{{ scope.row?.merchantUser?.mobile }}</span>
        </template>
        <template #subjectType="scope">
          <el-tag type="primary" class="margin-r-10">
            {{ SUBJECT_TYPE_ENUM_ALL_OBJECT[scope.row.subjectType] }}
          </el-tag>
        </template>
        <template #status="scope">
          <el-tag v-if="scope.row.status == 1" type="success" class="margin-r-10">通过</el-tag>
          <el-tag v-if="scope.row.status == 2" type="danger" class="margin-r-10">驳回</el-tag>
          <el-tag v-if="scope.row.status == 0" type="warning">未审核</el-tag>
        </template>
        <template #handle="scope">
          <el-button link type="primary" :disabled="scope.row.status == 1 || scope.row.status == 2"
            @click="handleAudit(scope.row, MERCHANT_APPLY_AUDIT_STATUS_WORD['入驻通过'])">
            通过
          </el-button>
          <el-button link type="danger" :disabled="scope.row.status == 1 || scope.row.status == 2"
            @click="handleAudit(scope.row, MERCHANT_APPLY_AUDIT_STATUS_WORD['入驻失败'])">
            驳回
          </el-button>
          <el-button link type="info" @click="handleView(scope.row, 3)">查看</el-button>
        </template>
      </base-page-table>
    </div>

    <Detail v-model:visible="dialogVisible" :row="activeRow" :type="activeName" />
    <audit-form ref="auditFormRef" @submit="audit"></audit-form>
    <reject-dialog ref="rejectDialogRef" @submit="rejectSubmit"></reject-dialog>
  </div>
</template>
<script setup>
// import BasePageTable from '@/components/BasePageTable'
// import TagSelect from '@/components/TagSelect'
import RejectDialog from "@/views/audit/enter/components/reject-dialog.vue";
import Detail from "./Detail.vue";
import {
  getMerchantCompanyList,
  getMerchantEmployeeList,
  auditMerchantCompany,
  auditMerchantEmployee,
} from "@/api/apply/index";
import { MERCHANT_APPLY_AUDIT_STATUS_WORD } from "@/utils/enums/merchant";
import { tableCompanyColumnsData, tableEmployeeColumnsData } from "./utils/enum";
import { SUBJECT_TYPE_ENUM_ALL_OBJECT } from "@/utils/enums/system";
import { ref } from "vue";
import AuditForm from "@/views/audit/enter/components/audit-form.vue";
import { getCompanyEnterInfo } from "@/api/apply/audit.ts";
const auditFormRef = ref();
const dialogVisible = ref(false);
const loading = ref(false);
const statusList = ref([
  {
    label: "未审核",
    value: 0,
  },
  {
    label: "通过",
    value: 1,
  },
  {
    label: "驳回",
    value: 2,
  },
]);
// const tagList = ref([
//     ...SUBJECT_TYPE_ENUM_ALL,
// ])
//const defaultTags = ref([tagList.value[0].value])
const handleReset = () => {
  queryParams.status = "";
  queryParams.keyword = "";
  queryParams.startDate = "";
  queryParams.endDate = "";
  queryParams.pageNum = 1;
  queryParams.pageSize = 10;
  queryParams.total = 0;
  tempTime.value = [];
  baseClick();
};
const handleSearch = () => {
  queryParams.pageNum = 1;
  baseClick();
};
const tempTime = ref();
function handleChange(val) {
  if (val) {
    const [startTime, endTime] = val;
    queryParams.startDate = startTime || "";
    queryParams.endDate = endTime || "";
  } else {
    queryParams.startDate = "";
    queryParams.endDate = "";
  }
}
const queryParams = reactive({
  keyword: undefined,
  status: undefined,
  startDate: "",
  endDate: "",
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
const activeName = ref("company");

const handleClick = (tab) => {
  queryParams.pageNum = 1;
  tableData.value = [];
  baseClick();
};
const baseClick = () => {
  loading.value = true;
  const isEmployee = activeName.value == "designer";
  if (isEmployee) {
    tableColumnsData.value = [...tableEmployeeColumnsData];
    funcGetMerchantList("company");
  } else {
    tableColumnsData.value = [...tableCompanyColumnsData];
    funcGetMerchantList("employee");
  }
};
const tableColumnsData = ref([...tableCompanyColumnsData]);

// const handleChangeTag = (tags) => {
//     console.log(tags, SYSTEM_TYPE_REVERSE_OBJECT['设计师'], 'tags83e7827238472387')
//     console.log(tags.includes(`${SYSTEM_TYPE_REVERSE_OBJECT['设计师']}`), 'tags83e7827238472387')

//     if (tags.includes(`${SYSTEM_TYPE_REVERSE_OBJECT['设计师']}`)) {
//         tableColumnsData.value = [...tableEmployeeColumnsData]
//         funcGetMerchantList('employee')
//     } else {
//         tableColumnsData.value = [...tableCompanyColumnsData]
//         funcGetMerchantList('company')
//     }
// }
const tableData = ref([]);
/**
 * 操作 - 审核通过，还是驳回
 * @param row
 * @param status
 */
const rejectDialogRef = ref();
const handleAudit = async (row, status) => {
  // 如果是公司，并且成功需要地图选点确定位置
  if (activeName.value == "company" && status == MERCHANT_APPLY_AUDIT_STATUS_WORD["入驻通过"]) {
    auditFormRef.value.showModal(row, status);
    return;
  }
  // 如果是驳回，则需要弹出驳回原因弹窗
  if (status == MERCHANT_APPLY_AUDIT_STATUS_WORD["入驻失败"]) {
    rejectDialogRef.value.showModal(row, status);
    return;
  }
  // 如果是通过，则直接审核
  const result = await ElMessageBox.confirm(`确认${status == 1 ? "通过" : "驳回"}吗?`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });
  if (!result) return;
  //const type = row.type === '个人' ? 'employee' : 'company'
  funcAuditMerchantApply(activeName.value, {
    id: row.id,
    status: status,
  });
};
const rejectSubmit = async (formData, status) => {
  funcAuditMerchantApply(activeName.value, {
    id: formData.id,
    status: status,
    remark: formData.remark,
  });
};
const audit = async (row, status) => {
  const { latitude, longitude, mallCommission, categoryCommission } = row;
  funcAuditMerchantApply(activeName.value, {
    id: row.id,
    status: status,
    latitude,
    longitude,
    mallCommission,
    categoryCommission,
  });
};
/**
 * 请求相关
 *
 */
//获取入驻审核列表
const funcGetMerchantList = async (type) => {
  let params = {
    keyword: queryParams.keyword,
    startDate: queryParams.startDate,
    endDate: queryParams.endDate,
    pageNum: queryParams.pageNum,
    pageSize: queryParams.pageSize,
  };
  if (queryParams.status !== undefined) {
    params.status = queryParams.status;
  }
  try {
    let res;
    if (type === "company") {
      res = await getMerchantCompanyList(params);
    } else {
      params.queryUser = true;
      res = await getMerchantEmployeeList(params);
    }
    console.log(res);

    tableData.value = res.data;
    queryParams.total = res.total;
    // 刷新列表
  } catch (err) {
    console.log(err);
  } finally {
    loading.value = false;
  }
};
//审核入驻申请
const funcAuditMerchantApply = async (type, params) => {
  let apiRequest = type === "company" ? auditMerchantCompany : auditMerchantEmployee;
  try {
    const res = await apiRequest(params);
    baseClick();
    // 刷新列表
  } catch (err) {
    console.log(err);
  } finally {
  }
};
function handleQuery(val) {
  queryParams.pageNum = val.pageNum;
  queryParams.pageSize = val.pageSize;
  baseClick();
}
const activeRow = ref(null);
const handleView = async (row, status) => {
  try {
    const res = await getCompanyEnterInfo(row.merchantUser?.userId);
    activeRow.value = res.data || {};
    if (activeName.value == "designer") {
      activeRow.value.nickname = row.merchantUserVO.nickname;
      activeRow.value.mobile = row.merchantUserVO.mobile;
    }
    dialogVisible.value = true;
  } catch (e) {
    console.error(e);
  } finally {
  }
};
onMounted(() => {
  baseClick();
});
</script>
<style lang="scss" scoped>
.table-container {
  flex: 1;
  display: flex;
  background-color: #fff;
  padding: 0px 20px;
}

.enter-tabs {
  background-color: #fff;
  padding: 10px 20px;
}
</style>
